{% extends "后台管理/template.html" %}

{% block title %}活动审批{% endblock %}

{% block nav_left %}
{% include "后台管理/components/左侧导航栏.html" %}
{% endblock %}

{% block css %}
<style>
    .approval-card {
        transition: all 0.3s ease;
    }
    
    .approval-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .status-badge {
        position: absolute;
        top: 10px;
        right: 10px;
    }

    .reward-image {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold py-3 mb-4">活动审批</h4>
        <div class="btn-group">
            <button class="btn btn-primary" onclick="refreshData()">
                <i class="bx bx-refresh me-1"></i> 刷新数据
            </button>
        </div>
    </div>

    <!-- 筛选条件 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">状态筛选</label>
                    <select class="form-select" id="statusFilter" onchange="loadParticipations()">
                        <option value="">全部状态</option>
                        <option value="1">未审核</option>
                        <option value="2">不通过</option>
                        <option value="3">通过</option>
                        <option value="5">进行中</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- 审批列表 -->
    <div class="row g-4" id="participationList">
        <!-- 参与记录将通过JS动态加载 -->
    </div>

    <!-- 备注详情模态框 -->
    <div class="modal fade" id="remarkModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">审批备注详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="fullRemark" class="mb-0"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- 审批模态框 -->
    <div class="modal fade" id="approvalModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">审批活动</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="approvalForm">
                        <input type="hidden" id="participationId">
                        <input type="hidden" id="activityId">
                        <input type="hidden" id="userId">
                        
                        <div class="mb-3">
                            <label class="form-label">审批结果</label>
                            <select class="form-select" id="approvalStatus" required>
                                <option value="3">通过</option>
                                <option value="2">不通过</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">审批备注</label>
                            <textarea class="form-control" id="approvalRemark" rows="3" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitApproval()">提交审批</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let approvalModal;
let remarkModal;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    approvalModal = new bootstrap.Modal(document.getElementById('approvalModal'));
    remarkModal = new bootstrap.Modal(document.getElementById('remarkModal'));
    loadParticipations();
});

// 加载参与记录
async function loadParticipations() {
    try {
        const status = document.getElementById('statusFilter').value;
        const response = await fetch(`/api/participation/approval/list/?status=${status}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderParticipations(data.data);
        }
    } catch (error) {
        console.error('加载参与记录失败:', error);
    }
}

// 显示完整备注
function showFullRemark(remark) {
    document.getElementById('fullRemark').textContent = remark;
    remarkModal.show();
}

// 处理备注显示
function formatRemark(remark) {
    if (!remark) return '';
    if (remark.length <= 50) {
        return `<div class="mt-3">
            <small class="text-muted">审批备注: ${remark}</small>
        </div>`;
    }
    return `<div class="mt-3 d-flex align-items-center">
        <small class="text-muted text-truncate" style="max-width: 200px;">审批备注: ${remark}</small>
        <button class="btn btn-sm btn-text-secondary ms-2" onclick="showFullRemark('${remark.replace(/'/g, "\\'")}')">
            <i class="bx bx-expand"></i> 查看完整
        </button>
    </div>`;
}

// 渲染参与记录
function renderParticipations(participations) {
    const container = document.getElementById('participationList');
    container.innerHTML = participations.map(item => `
        <div class="col-md-6 col-lg-4">
            <div class="card approval-card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="flex-shrink-0">
                            <img src="${item.reward?.image || '/static/images/default.png'}" 
                                 class="reward-image" alt="奖品图片">
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h5 class="card-title mb-1">${item.activity.title}</h5>
                            <p class="card-text text-muted">
                                参与者: ${item.user.username}
                            </p>
                        </div>
                    </div>
                    <div class="mb-3">
                        <small class="text-muted">
                            参与时间: ${new Date(item.created_at).toLocaleString()}
                        </small>
                        ${item.completion_time ? `
                        <br>
                        <small class="text-muted">
                            完成时间: ${new Date(item.completion_time).toLocaleString()}
                        </small>
                        ` : ''}
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="badge bg-${getStatusBadgeClass(item.status)}">
                            ${getStatusText(item.status)}
                        </span>
                        ${item.status === 1 ? `
                        <button class="btn btn-primary btn-sm" 
                                onclick="openApprovalModal('${item.id}', '${item.activity.id}', '${item.user.user_id}')">
                            审批
                        </button>
                        ` : ''}
                    </div>
                    ${formatRemark(item.remark)}
                </div>
            </div>
        </div>
    `).join('');
}

// 打开审批模态框
function openApprovalModal(participationId, activityId, userId) {
    document.getElementById('participationId').value = participationId;
    document.getElementById('activityId').value = activityId;
    document.getElementById('userId').value = userId;
    approvalModal.show();
}

// 提交审批
async function submitApproval() {
    try {
        const formData = new FormData();
        formData.append('participation_id', document.getElementById('participationId').value);
        formData.append('activity_id', document.getElementById('activityId').value);
        formData.append('user_id', document.getElementById('userId').value);
        formData.append('status', document.getElementById('approvalStatus').value);
        formData.append('remark', document.getElementById('approvalRemark').value);

        const response = await fetch('/api/participation/approve/', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        if (data.code === 200) {
            showToast('审批成功', 'success');
            approvalModal.hide();
            loadParticipations();
        } else {
            showToast(data.message, 'error');
        }
    } catch (error) {
        console.error('提交审批失败:', error);
        showToast('提交审批失败', 'error');
    }
}

// 获取状态样式
function getStatusBadgeClass(status) {
    const statusMap = {
        1: 'warning',   // 未审核
        2: 'danger',    // 不通过
        3: 'success',   // 通过
        4: 'secondary', // 默认状态
        5: 'info'       // 进行中
    };
    return statusMap[status] || 'primary';
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        1: '未审核',
        2: '不通过',
        3: '通过',
        4: '默认状态',
        5: '进行中'
    };
    return statusMap[status] || '未知状态';
}

// 显示通知
function showToast(message, type = 'success') {
    const container = document.querySelector('.toast-container') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast-notification toast-${type}`;
    
    const closeBtn = document.createElement('button');
    closeBtn.className = 'btn-close';
    closeBtn.onclick = () => toast.remove();
    
    let icon;
    switch (type) {
        case 'success':
            icon = '<i class="bx bx-check-circle me-2"></i>';
            break;
        case 'error':
            icon = '<i class="bx bx-x-circle me-2"></i>';
            break;
        case 'warning':
            icon = '<i class="bx bx-error-circle me-2"></i>';
            break;
    }
    
    toast.innerHTML = `
        <div class="d-flex align-items-center">
            ${icon}
            <span>${message}</span>
        </div>
    `;
    toast.appendChild(closeBtn);
    
    container.appendChild(toast);
    
    setTimeout(() => {
        if (toast && toast.parentElement) {
            toast.style.animation = 'fadeOut 0.3s ease forwards';
            setTimeout(() => toast.remove(), 300);
        }
    }, 3000);
}

// 创建通知容器
function createToastContainer() {
    const container = document.createElement('div');
    container.className = 'toast-container';
    document.body.appendChild(container);
    return container;
}

// 刷新数据
function refreshData() {
    loadParticipations();
}
</script>
{% endblock %}

{% block footer %}{% include '后台管理/components/Footer.html' %}{% endblock %}
